package com.sj.purchase.modules.cost.config.task.compute;

import com.sj.purchase.modules.cost.config.task.TaskManager;
import com.sj.purchase.modules.cost.event.RunTaskEvent;
import com.sj.purchase.modules.cost.domain.SucTask;
import com.sj.purchase.modules.cost.publisher.CustomPublisher;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by yangrd on 2017/11/8
 **/
@Component
public class ComputeTaskManager implements TaskManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(ComputeTaskManager.class);

    private CostPriceTask costPriceTask;

    private StockContrastTask stockContrastTask;

    private CustomPublisher publisher;

    public ComputeTaskManager(CostPriceTask costPriceTask, StockContrastTask stockContrastTask, CustomPublisher publisher) {
        this.costPriceTask = costPriceTask;
        this.stockContrastTask = stockContrastTask;
        this.publisher = publisher;
    }

    @Override
    public void runTask(SucTask.TaskType taskType, Date taskDay) {
        String taskDayStr = DateFormatUtils.format(taskDay, "yyyy/MM/dd");
        switch (taskType) {
            case COMPUTE_COST_PRICE:
                LOGGER.info("[{}] :=> 开始计算平均价", taskDayStr);
                costPriceTask.calculateTheCostPrice(taskDay);
                publishEvent(new RunTaskEvent(this, taskType, taskDay));
                break;
            case COMPUTE_STOCK_CONTRAST:
                LOGGER.info("[{}] :=> 开始计算库存对比", taskDayStr);
                Boolean computeSuccess = stockContrastTask.contrast(taskDay);
                if(computeSuccess){
                    publishEvent(new RunTaskEvent(this, taskType, taskDay));
                }
                break;
            default:
                throw new RuntimeException("");
        }
    }

    private void publishEvent(ApplicationEvent applicationEvent) {
        publisher.publishEvent(applicationEvent);
    }
}
